package br.com.sgp.util.handling;

import org.apache.log4j.Logger;
import org.apache.wicket.feedback.FeedbackMessage;
import org.apache.wicket.feedback.FeedbackMessagesModel;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;

import br.com.ufpr.util.base.BasePage;

public class ErrorHandlingForm<T> extends Form<T> {
    private static final long serialVersionUID = 1476941837207678151L;

    private static final Logger log = Logger.getLogger(ErrorHandlingForm.class);

    public ErrorHandlingForm(String id) {
        super(id);
    }

    public ErrorHandlingForm(String id, IModel<T> model) {
        super(id, new CompoundPropertyModel<T>(model));
    }

    @Override
    protected void onError() {
        log.debug("Erro no form... Exibindo painel de mensagens...");
        super.onError();

        final FeedbackPanel feed = new FeedbackPanel("feedback1") {
            private static final long serialVersionUID = -6809494832998670701L;

            @Override
            protected FeedbackMessagesModel newFeedbackMessagesModel() {
                return new FeedbackMessagesModel(((BasePage) ErrorHandlingForm.this.getPage()));
            }

        };

        for (FeedbackMessage msg : feed.getFeedbackMessagesModel().getObject()) {
            ((BasePage) ErrorHandlingForm.this.getPage()).adicionaMensagemErro(msg.getMessage().toString());
        }

        ((BasePage) ErrorHandlingForm.this.getPage()).atualizarFeedbackPanel();

    }

}
